Don't place html in alt/title attributes, especially with thumbnails
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27 var $tooBig = false;
28 var $kblength = false;
29 var $missingComment = false;
30
31 # Form values
32 var $save = false, $preview = false, $diff = false;
33 var $minoredit = false, $watchthis = false, $recreate = false;
34 var $textbox1 = '', $textbox2 = '', $summary = '';
35 var $edittime = '', $section = '', $starttime = '';
36 var $oldid = 0, $editintro = '', $scrolltop = null;
37
38 /**
39 * @todo document
40 * @param $article
41 */
42 function EditPage( $article ) {
43 $this->mArticle =& $article;
44 global $wgTitle;
45 $this->mTitle =& $wgTitle;
46 }
47
48 /**
49 * This is the function that extracts metadata from the article body on the first view.
50 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
51 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
52 */
53 function extractMetaDataFromArticle () {
54 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
55 $this->mMetaData = '' ;
56 if ( !$wgUseMetadataEdit ) return ;
57 if ( $wgMetadataWhitelist == '' ) return ;
58 $s = '' ;
59 $t = $this->mArticle->getContent();
60
61 # MISSING : <nowiki> filtering
62
63 # Categories and language links
64 $t = explode ( "\n" , $t ) ;
65 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
66 $cat = $ll = array() ;
67 foreach ( $t AS $key => $x )
68 {
69 $y = trim ( strtolower ( $x ) ) ;
70 while ( substr ( $y , 0 , 2 ) == '[[' )
71 {
72 $y = explode ( ']]' , trim ( $x ) ) ;
73 $first = array_shift ( $y ) ;
74 $first = explode ( ':' , $first ) ;
75 $ns = array_shift ( $first ) ;
76 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
77 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
78 {
79 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
80 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
81 else $ll[] = $add ;
82 $x = implode ( ']]' , $y ) ;
83 $t[$key] = $x ;
84 $y = trim ( strtolower ( $x ) ) ;
85 }
86 }
87 }
88 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
89 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
90 $t = implode ( "\n" , $t ) ;
91
92 # Load whitelist
93 $sat = array () ; # stand-alone-templates; must be lowercase
94 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
95 $wl_article = new Article ( $wl_title ) ;
96 $wl = explode ( "\n" , $wl_article->getContent() ) ;
97 foreach ( $wl AS $x )
98 {
99 $isentry = false ;
100 $x = trim ( $x ) ;
101 while ( substr ( $x , 0 , 1 ) == '*' )
102 {
103 $isentry = true ;
104 $x = trim ( substr ( $x , 1 ) ) ;
105 }
106 if ( $isentry )
107 {
108 $sat[] = strtolower ( $x ) ;
109 }
110
111 }
112
113 # Templates, but only some
114 $t = explode ( '{{' , $t ) ;
115 $tl = array () ;
116 foreach ( $t AS $key => $x )
117 {
118 $y = explode ( '}}' , $x , 2 ) ;
119 if ( count ( $y ) == 2 )
120 {
121 $z = $y[0] ;
122 $z = explode ( '|' , $z ) ;
123 $tn = array_shift ( $z ) ;
124 if ( in_array ( strtolower ( $tn ) , $sat ) )
125 {
126 $tl[] = '{{' . $y[0] . '}}' ;
127 $t[$key] = $y[1] ;
128 $y = explode ( '}}' , $y[1] , 2 ) ;
129 }
130 else $t[$key] = '{{' . $x ;
131 }
132 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
133 else $t[$key] = $x ;
134 }
135 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
136 $t = implode ( '' , $t ) ;
137
138 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
139 $this->mArticle->mContent = $t ;
140 $this->mMetaData = $s ;
141 }
142
143 function submit() {
144 $this->edit();
145 }
146
147 /**
148 * This is the function that gets called for "action=edit". It
149 * sets up various member variables, then passes execution to
150 * another function, usually showEditForm()
151 *
152 * The edit form is self-submitting, so that when things like
153 * preview and edit conflicts occur, we get the same form back
154 * with the extra stuff added. Only when the final submission
155 * is made and all is well do we actually save and redirect to
156 * the newly-edited page.
157 */
158 function edit() {
159 global $wgOut, $wgUser, $wgRequest, $wgTitle;
160 global $wgEmailConfirmToEdit;
161
162 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
163 return;
164
165 $fname = 'EditPage::edit';
166 wfProfileIn( $fname );
167 wfDebug( "$fname: enter\n" );
168
169 // this is not an article
170 $wgOut->setArticleFlag(false);
171
172 $this->importFormData( $wgRequest );
173 $this->firsttime = false;
174
175 if( $this->live ) {
176 $this->livePreview();
177 wfProfileOut( $fname );
178 return;
179 }
180
181 if ( ! $this->mTitle->userCanEdit() ) {
182 wfDebug( "$fname: user can't edit\n" );
183 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
184 wfProfileOut( $fname );
185 return;
186 }
187 wfDebug( "$fname: Checking blocks\n" );
188 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
189 # When previewing, don't check blocked state - will get caught at save time.
190 # Also, check when starting edition is done against slave to improve performance.
191 wfDebug( "$fname: user is blocked\n" );
192 $wgOut->blockedPage();
193 wfProfileOut( $fname );
194 return;
195 }
196 if ( !$wgUser->isAllowed('edit') ) {
197 if ( $wgUser->isAnon() ) {
198 wfDebug( "$fname: user must log in\n" );
199 $this->userNotLoggedInPage();
200 wfProfileOut( $fname );
201 return;
202 } else {
203 wfDebug( "$fname: read-only page\n" );
204 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
205 wfProfileOut( $fname );
206 return;
207 }
208 }
209 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
210 wfDebug("$fname: user must confirm e-mail address\n");
211 $this->userNotConfirmedPage();
212 wfProfileOut($fname);
213 return;
214 }
215 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
216 wfDebug( "$fname: no create permission\n" );
217 $this->noCreatePermission();
218 wfProfileOut( $fname );
219 return;
220 }
221 if ( wfReadOnly() ) {
222 wfDebug( "$fname: read-only mode is engaged\n" );
223 if( $this->save || $this->preview ) {
224 $this->formtype = 'preview';
225 } else if ( $this->diff ) {
226 $this->formtype = 'diff';
227 } else {
228 $wgOut->readOnlyPage( $this->mArticle->getContent() );
229 wfProfileOut( $fname );
230 return;
231 }
232 } else {
233 if ( $this->save ) {
234 $this->formtype = 'save';
235 } else if ( $this->preview ) {
236 $this->formtype = 'preview';
237 } else if ( $this->diff ) {
238 $this->formtype = 'diff';
239 } else { # First time through
240 $this->firsttime = true;
241 if( $this->previewOnOpen() ) {
242 $this->formtype = 'preview';
243 } else {
244 $this->extractMetaDataFromArticle () ;
245 $this->formtype = 'initial';
246 }
247 }
248 }
249
250 wfProfileIn( "$fname-business-end" );
251
252 $this->isConflict = false;
253 // css / js subpages of user pages get a special treatment
254 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
255 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
256
257 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
258 * no matter it's current state
259 */
260 $this->deletedSinceEdit = false;
261 if ( $this->edittime != '' ) {
262 /* Note that we rely on logging table, which hasn't been always there,
263 * but that doesn't matter, because this only applies to brand new
264 * deletes. This is done on every preview and save request. Move it further down
265 * to only perform it on saves
266 */
267 if ( $this->mTitle->isDeleted() ) {
268 $this->lastDelete = $this->getLastDelete();
269 if ( !is_null($this->lastDelete) ) {
270 $deletetime = $this->lastDelete->log_timestamp;
271 if ( ($deletetime - $this->starttime) > 0 ) {
272 $this->deletedSinceEdit = true;
273 }
274 }
275 }
276 }
277
278 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
279 $this->showIntro();
280 }
281 if( $this->mTitle->isTalkPage() ) {
282 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
283 }
284
285 # Attempt submission here. This will check for edit conflicts,
286 # and redundantly check for locked database, blocked IPs, etc.
287 # that edit() already checked just in case someone tries to sneak
288 # in the back door with a hand-edited submission URL.
289
290 if ( 'save' == $this->formtype ) {
291 if ( !$this->attemptSave() ) {
292 wfProfileOut( "$fname-business-end" );
293 wfProfileOut( $fname );
294 return;
295 }
296 }
297
298 # First time through: get contents, set time for conflict
299 # checking, etc.
300 if ( 'initial' == $this->formtype || $this->firsttime ) {
301 $this->initialiseForm();
302 }
303
304 $this->showEditForm();
305 wfProfileOut( "$fname-business-end" );
306 wfProfileOut( $fname );
307 }
308
309 /**
310 * Return true if this page should be previewed when the edit form
311 * is initially opened.
312 * @return bool
313 * @access private
314 */
315 function previewOnOpen() {
316 global $wgUser;
317 return $this->section != 'new' &&
318 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
319 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
320 !$this->mTitle->exists() ) );
321 }
322
323 /**
324 * @todo document
325 */
326 function importFormData( &$request ) {
327 global $wgLang ;
328 $fname = 'EditPage::importFormData';
329 wfProfileIn( $fname );
330
331 if( $request->wasPosted() ) {
332 # These fields need to be checked for encoding.
333 # Also remove trailing whitespace, but don't remove _initial_
334 # whitespace from the text boxes. This may be significant formatting.
335 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
336 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
337 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
338 # Truncate for whole multibyte characters. +5 bytes for ellipsis
339 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
340
341 $this->edittime = $request->getVal( 'wpEdittime' );
342 $this->starttime = $request->getVal( 'wpStarttime' );
343
344 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
345
346 if( is_null( $this->edittime ) ) {
347 # If the form is incomplete, force to preview.
348 wfDebug( "$fname: Form data appears to be incomplete\n" );
349 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
350 $this->preview = true;
351 } else {
352 /* Fallback for live preview */
353 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
354 $this->diff = $request->getCheck( 'wpDiff' );
355
356 if( !$this->preview ) {
357 if ( $this->tokenOk( $request ) ) {
358 # Some browsers will not report any submit button
359 # if the user hits enter in the comment box.
360 # The unmarked state will be assumed to be a save,
361 # if the form seems otherwise complete.
362 wfDebug( "$fname: Passed token check.\n" );
363 } else {
364 # Page might be a hack attempt posted from
365 # an external site. Preview instead of saving.
366 wfDebug( "$fname: Failed token check; forcing preview\n" );
367 $this->preview = true;
368 }
369 }
370 }
371 $this->save = ! ( $this->preview OR $this->diff );
372 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
373 $this->edittime = null;
374 }
375
376 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
377 $this->starttime = null;
378 }
379
380 $this->recreate = $request->getCheck( 'wpRecreate' );
381
382 $this->minoredit = $request->getCheck( 'wpMinoredit' );
383 $this->watchthis = $request->getCheck( 'wpWatchthis' );
384 } else {
385 # Not a posted form? Start with nothing.
386 wfDebug( "$fname: Not a posted form.\n" );
387 $this->textbox1 = '';
388 $this->textbox2 = '';
389 $this->mMetaData = '';
390 $this->summary = '';
391 $this->edittime = '';
392 $this->starttime = wfTimestampNow();
393 $this->preview = false;
394 $this->save = false;
395 $this->diff = false;
396 $this->minoredit = false;
397 $this->watchthis = false;
398 $this->recreate = false;
399 }
400
401 $this->oldid = $request->getInt( 'oldid' );
402
403 # Section edit can come from either the form or a link
404 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
405
406 $this->live = $request->getCheck( 'live' );
407 $this->editintro = $request->getText( 'editintro' );
408
409 wfProfileOut( $fname );
410 }
411
412 /**
413 * Make sure the form isn't faking a user's credentials.
414 *
415 * @param WebRequest $request
416 * @return bool
417 * @access private
418 */
419 function tokenOk( &$request ) {
420 global $wgUser;
421 if( $wgUser->isAnon() ) {
422 # Anonymous users may not have a session
423 # open. Don't tokenize.
424 $this->mTokenOk = true;
425 } else {
426 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
427 }
428 return $this->mTokenOk;
429 }
430
431 function showIntro() {
432 global $wgOut, $wgUser;
433 $addstandardintro=true;
434 if($this->editintro) {
435 $introtitle=Title::newFromText($this->editintro);
436 if(isset($introtitle) && $introtitle->userCanRead()) {
437 $rev=Revision::newFromTitle($introtitle);
438 if($rev) {
439 $wgOut->addSecondaryWikiText($rev->getText());
440 $addstandardintro=false;
441 }
442 }
443 }
444 if($addstandardintro) {
445 if ( $wgUser->isLoggedIn() )
446 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
447 else
448 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
449 }
450 }
451
452 /**
453 * Attempt submission
454 * @return bool false if output is done, true if the rest of the form should be displayed
455 */
456 function attemptSave() {
457 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
458 global $wgMaxArticleSize;
459
460 $fname = 'EditPage::attemptSave';
461 wfProfileIn( $fname );
462 wfProfileIn( "$fname-checks" );
463
464 # Reintegrate metadata
465 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
466 $this->mMetaData = '' ;
467
468 # Check for spam
469 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
470 $this->spamPage ( $matches[0] );
471 wfProfileOut( "$fname-checks" );
472 wfProfileOut( $fname );
473 return false;
474 }
475 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
476 # Error messages or other handling should be performed by the filter function
477 wfProfileOut( $fname );
478 wfProfileOut( "$fname-checks" );
479 return false;
480 }
481 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
482 # Error messages or other handling should be performed by the filter function
483 wfProfileOut( $fname );
484 wfProfileOut( "$fname-checks" );
485 return false;
486 }
487 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
488 # Check block state against master, thus 'false'.
489 $this->blockedIPpage();
490 wfProfileOut( "$fname-checks" );
491 wfProfileOut( $fname );
492 return false;
493 }
494 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
495 if ( $this->kblength > $wgMaxArticleSize ) {
496 // Error will be displayed by showEditForm()
497 $this->tooBig = true;
498 wfProfileOut( "$fname-checks" );
499 wfProfileOut( $fname );
500 return true;
501 }
502
503 if ( !$wgUser->isAllowed('edit') ) {
504 if ( $wgUser->isAnon() ) {
505 $this->userNotLoggedInPage();
506 wfProfileOut( "$fname-checks" );
507 wfProfileOut( $fname );
508 return false;
509 }
510 else {
511 $wgOut->readOnlyPage();
512 wfProfileOut( "$fname-checks" );
513 wfProfileOut( $fname );
514 return false;
515 }
516 }
517
518 if ( wfReadOnly() ) {
519 $wgOut->readOnlyPage();
520 wfProfileOut( "$fname-checks" );
521 wfProfileOut( $fname );
522 return false;
523 }
524 if ( $wgUser->pingLimiter() ) {
525 $wgOut->rateLimited();
526 wfProfileOut( "$fname-checks" );
527 wfProfileOut( $fname );
528 return false;
529 }
530
531 # If the article has been deleted while editing, don't save it without
532 # confirmation
533 if ( $this->deletedSinceEdit && !$this->recreate ) {
534 wfProfileOut( "$fname-checks" );
535 wfProfileOut( $fname );
536 return true;
537 }
538
539 wfProfileOut( "$fname-checks" );
540
541 # If article is new, insert it.
542 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
543 if ( 0 == $aid ) {
544 // Late check for create permission, just in case *PARANOIA*
545 if ( !$this->mTitle->userCan( 'create' ) ) {
546 wfDebug( "$fname: no create permission\n" );
547 $this->noCreatePermission();
548 wfProfileOut( $fname );
549 return;
550 }
551
552 # Don't save a new article if it's blank.
553 if ( ( '' == $this->textbox1 ) ) {
554 $wgOut->redirect( $this->mTitle->getFullURL() );
555 wfProfileOut( $fname );
556 return false;
557 }
558
559 $isComment=($this->section=='new');
560 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
561 $this->minoredit, $this->watchthis, false, $isComment);
562
563 wfProfileOut( $fname );
564 return false;
565 }
566
567 # Article exists. Check for edit conflict.
568
569 $this->mArticle->clear(); # Force reload of dates, etc.
570 $this->mArticle->forUpdate( true ); # Lock the article
571
572 if( $this->mArticle->getTimestamp() != $this->edittime ) {
573 $this->isConflict = true;
574 if( $this->section == 'new' ) {
575 if( $this->mArticle->getUserText() == $wgUser->getName() &&
576 $this->mArticle->getComment() == $this->summary ) {
577 // Probably a duplicate submission of a new comment.
578 // This can happen when squid resends a request after
579 // a timeout but the first one actually went through.
580 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
581 } else {
582 // New comment; suppress conflict.
583 $this->isConflict = false;
584 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
585 }
586 }
587 }
588 $userid = $wgUser->getID();
589
590 if ( $this->isConflict) {
591 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
592 $this->mArticle->getTimestamp() . "'\n" );
593 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
594 }
595 else {
596 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
597 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
598 }
599 if( is_null( $text ) ) {
600 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
601 $this->isConflict = true;
602 $text = $this->textbox1;
603 }
604
605 # Suppress edit conflict with self, except for section edits where merging is required.
606 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
607 wfDebug( "Suppressing edit conflict, same user.\n" );
608 $this->isConflict = false;
609 } else {
610 # switch from section editing to normal editing in edit conflict
611 if($this->isConflict) {
612 # Attempt merge
613 if( $this->mergeChangesInto( $text ) ){
614 // Successful merge! Maybe we should tell the user the good news?
615 $this->isConflict = false;
616 wfDebug( "Suppressing edit conflict, successful merge.\n" );
617 } else {
618 $this->section = '';
619 $this->textbox1 = $text;
620 wfDebug( "Keeping edit conflict, failed merge.\n" );
621 }
622 }
623 }
624
625 if ( $this->isConflict ) {
626 wfProfileOut( $fname );
627 return true;
628 }
629
630 # All's well
631 wfProfileIn( "$fname-sectionanchor" );
632 $sectionanchor = '';
633 if( $this->section == 'new' ) {
634 if ( $this->textbox1 == '' ) {
635 $this->missingComment = true;
636 return true;
637 }
638 if( $this->summary != '' ) {
639 $sectionanchor = $this->sectionAnchor( $this->summary );
640 }
641 } elseif( $this->section != '' ) {
642 # Try to get a section anchor from the section source, redirect to edited section if header found
643 # XXX: might be better to integrate this into Article::replaceSection
644 # for duplicate heading checking and maybe parsing
645 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
646 # we can't deal with anchors, includes, html etc in the header for now,
647 # headline would need to be parsed to improve this
648 if($hasmatch and strlen($matches[2]) > 0) {
649 $sectionanchor = $this->sectionAnchor( $matches[2] );
650 }
651 }
652 wfProfileOut( "$fname-sectionanchor" );
653
654 // Save errors may fall down to the edit form, but we've now
655 // merged the section into full text. Clear the section field
656 // so that later submission of conflict forms won't try to
657 // replace that into a duplicated mess.
658 $this->textbox1 = $text;
659 $this->section = '';
660
661 // Check for length errors again now that the section is merged in
662 $this->kblength = (int)(strlen( $text ) / 1024);
663 if ( $this->kblength > $wgMaxArticleSize ) {
664 $this->tooBig = true;
665 wfProfileOut( $fname );
666 return true;
667 }
668
669 # update the article here
670 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
671 $this->watchthis, '', $sectionanchor ) ) {
672 wfProfileOut( $fname );
673 return false;
674 } else {
675 $this->isConflict = true;
676 }
677 wfProfileOut( $fname );
678 return true;
679 }
680
681 /**
682 * Initialise form fields in the object
683 * Called on the first invocation, e.g. when a user clicks an edit link
684 */
685 function initialiseForm() {
686 $this->edittime = $this->mArticle->getTimestamp();
687 $this->textbox1 = $this->mArticle->getContent();
688 $this->summary = '';
689 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
690 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
691 wfProxyCheck();
692 }
693
694 /**
695 * Send the edit form and related headers to $wgOut
696 * @param $formCallback Optional callable that takes an OutputPage
697 * parameter; will be called during form output
698 * near the top, for captchas and the like.
699 */
700 function showEditForm( $formCallback=null ) {
701 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
702
703 $fname = 'EditPage::showEditForm';
704 wfProfileIn( $fname );
705
706 $sk =& $wgUser->getSkin();
707
708 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
709
710 $wgOut->setRobotpolicy( 'noindex,nofollow' );
711
712 # Enabled article-related sidebar, toplinks, etc.
713 $wgOut->setArticleRelated( true );
714
715 if ( $this->isConflict ) {
716 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
717 $wgOut->setPageTitle( $s );
718 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
719
720 $this->textbox2 = $this->textbox1;
721 $this->textbox1 = $this->mArticle->getContent();
722 $this->edittime = $this->mArticle->getTimestamp();
723 } else {
724
725 if( $this->section != '' ) {
726 if( $this->section == 'new' ) {
727 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
728 } else {
729 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
730 if( !$this->preview && !$this->diff ) {
731 preg_match( "/^(=+)(.+)\\1/mi",
732 $this->textbox1,
733 $matches );
734 if( !empty( $matches[2] ) ) {
735 $this->summary = "/* ". trim($matches[2])." */ ";
736 }
737 }
738 }
739 } else {
740 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
741 }
742 $wgOut->setPageTitle( $s );
743
744 if ( $this->missingComment ) {
745 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
746 }
747
748 if ( !$this->checkUnicodeCompliantBrowser() ) {
749 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
750 }
751 if ( isset( $this->mArticle )
752 && isset( $this->mArticle->mRevision )
753 && !$this->mArticle->mRevision->isCurrent() ) {
754 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
755 $wgOut->addWikiText( wfMsg( 'editingold' ) );
756 }
757 }
758
759 if( wfReadOnly() ) {
760 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
761 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
762 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
763 } else {
764 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
765 # Check the skin exists
766 if( $this->isValidCssJsSubpage ) {
767 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
768 } else {
769 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
770 }
771 }
772 }
773
774 if( $this->mTitle->isProtected( 'edit' ) ) {
775 if( $this->mTitle->isSemiProtected() ) {
776 $notice = wfMsg( 'semiprotectedpagewarning' );
777 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
778 $notice = '';
779 }
780 } else {
781 $notice = wfMsg( 'protectedpagewarning' );
782 }
783 $wgOut->addWikiText( $notice );
784 }
785
786 if ( $this->kblength === false ) {
787 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
788 }
789 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
790 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
791 } elseif( $this->kblength > 29 ) {
792 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
793 }
794
795 $rows = $wgUser->getOption( 'rows' );
796 $cols = $wgUser->getOption( 'cols' );
797
798 $ew = $wgUser->getOption( 'editwidth' );
799 if ( $ew ) $ew = " style=\"width:100%\"";
800 else $ew = '';
801
802 $q = 'action=submit';
803 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
804 $action = $this->mTitle->escapeLocalURL( $q );
805
806 $summary = wfMsg('summary');
807 $subject = wfMsg('subject');
808 $minor = wfMsg('minoredit');
809 $watchthis = wfMsg ('watchthis');
810
811 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
812 wfMsg('cancel') );
813 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
814 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
815 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
816 htmlspecialchars( wfMsg( 'newwindow' ) );
817
818 global $wgRightsText;
819 $copywarn = "<div id=\"editpage-copywarn\">\n" .
820 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
821 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
822 $wgRightsText ) . "\n</div>";
823
824 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
825 # prepare toolbar for edit buttons
826 $toolbar = $this->getEditToolbar();
827 } else {
828 $toolbar = '';
829 }
830
831 // activate checkboxes if user wants them to be always active
832 if( !$this->preview && !$this->diff ) {
833 # Sort out the "watch" checkbox
834 if( $wgUser->getOption( 'watchdefault' ) ) {
835 # Watch all edits
836 $this->watchthis = true;
837 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
838 # Watch creations
839 $this->watchthis = true;
840 } elseif( $this->mTitle->userIsWatching() ) {
841 # Already watched
842 $this->watchthis = true;
843 }
844
845 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
846 }
847
848 $minoredithtml = '';
849
850 if ( $wgUser->isAllowed('minoredit') ) {
851 $minoredithtml =
852 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
853 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
854 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
855 }
856
857 $watchhtml = '';
858
859 if ( $wgUser->isLoggedIn() ) {
860 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
861 ($this->watchthis?" checked='checked'":"").
862 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
863 "<label for='wpWatchthis' title=\"" .
864 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
865 }
866
867 $checkboxhtml = $minoredithtml . $watchhtml;
868
869 if ( $wgUser->getOption( 'previewontop' ) ) {
870
871 if ( 'preview' == $this->formtype ) {
872 $this->showPreview();
873 } else {
874 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
875 }
876
877 if ( 'diff' == $this->formtype ) {
878 $wgOut->addHTML( $this->getDiff() );
879 }
880 }
881
882
883 # if this is a comment, show a subject line at the top, which is also the edit summary.
884 # Otherwise, show a summary field at the bottom
885 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
886 if( $this->section == 'new' ) {
887 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
888 $editsummary = '';
889 } else {
890 $commentsubject = '';
891 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
892 }
893
894 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
895 if( !$this->preview && !$this->diff ) {
896 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
897 }
898 $templates = $this->formatTemplates();
899
900 global $wgUseMetadataEdit ;
901 if ( $wgUseMetadataEdit ) {
902 $metadata = $this->mMetaData ;
903 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
904 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
905 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
906 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
907 }
908 else $metadata = "" ;
909
910 $hidden = '';
911 $recreate = '';
912 if ($this->deletedSinceEdit) {
913 if ( 'save' != $this->formtype ) {
914 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
915 } else {
916 // Hide the toolbar and edit area, use can click preview to get it back
917 // Add an confirmation checkbox and explanation.
918 $toolbar = '';
919 $hidden = 'type="hidden" style="display:none;"';
920 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
921 $recreate .=
922 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
923 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
924 }
925 }
926
927 $temp = array(
928 'id' => 'wpSave',
929 'name' => 'wpSave',
930 'type' => 'submit',
931 'tabindex' => '5',
932 'value' => wfMsg('savearticle'),
933 'accesskey' => wfMsg('accesskey-save'),
934 'title' => wfMsg('tooltip-save'),
935 );
936 $buttons['save'] = wfElement('input', $temp, '');
937 $temp = array(
938 'id' => 'wpDiff',
939 'name' => 'wpDiff',
940 'type' => 'submit',
941 'tabindex' => '7',
942 'value' => wfMsg('showdiff'),
943 'accesskey' => wfMsg('accesskey-diff'),
944 'title' => wfMsg('tooltip-diff'),
945 );
946 $buttons['diff'] = wfElement('input', $temp, '');
947
948 global $wgLivePreview;
949 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
950 $temp = array(
951 'id' => 'wpPreview',
952 'name' => 'wpPreview',
953 'type' => 'submit',
954 'tabindex' => '6',
955 'value' => wfMsg('showpreview'),
956 'accesskey' => '',
957 'title' => wfMsg('tooltip-preview'),
958 'style' => 'display: none;',
959 );
960 $buttons['preview'] = wfElement('input', $temp, '');
961 $temp = array(
962 'id' => 'wpLivePreview',
963 'name' => 'wpLivePreview',
964 'type' => 'submit',
965 'tabindex' => '6',
966 'value' => wfMsg('showlivepreview'),
967 'accesskey' => wfMsg('accesskey-preview'),
968 'title' => '',
969 'onclick' => $this->doLivePreviewScript(),
970 );
971 $buttons['live'] = wfElement('input', $temp, '');
972 } else {
973 $temp = array(
974 'id' => 'wpPreview',
975 'name' => 'wpPreview',
976 'type' => 'submit',
977 'tabindex' => '6',
978 'value' => wfMsg('showpreview'),
979 'accesskey' => wfMsg('accesskey-preview'),
980 'title' => wfMsg('tooltip-preview'),
981 );
982 $buttons['preview'] = wfElement('input', $temp, '');
983 $buttons['live'] = '';
984 }
985
986 $safemodehtml = $this->checkUnicodeCompliantBrowser()
987 ? ""
988 : "<input type='hidden' name=\"safemode\" value='1' />\n";
989
990 $wgOut->addHTML( <<<END
991 {$toolbar}
992 <form id="editform" name="editform" method="post" action="$action"
993 enctype="multipart/form-data">
994 END
995 );
996
997 if( is_callable( $formCallback ) ) {
998 call_user_func_array( $formCallback, array( &$wgOut ) );
999 }
1000
1001 // Put these up at the top to ensure they aren't lost on early form submission
1002 $wgOut->addHTML( "
1003 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1004 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1005 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1006 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1007
1008 $wgOut->addHTML( <<<END
1009 $recreate
1010 {$commentsubject}
1011 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1012 cols='{$cols}'{$ew} $hidden>
1013 END
1014 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1015 "
1016 </textarea>
1017 " );
1018
1019 $wgOut->addWikiText( $copywarn );
1020 $wgOut->addHTML( "
1021 {$metadata}
1022 {$editsummary}
1023 {$checkboxhtml}
1024 {$safemodehtml}
1025 ");
1026
1027 $wgOut->addHTML("
1028 <div class='editButtons'>
1029 {$buttons['save']}
1030 {$buttons['preview']}
1031 {$buttons['live']}
1032 {$buttons['diff']}
1033 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1034 </div><!-- editButtons -->
1035 </div><!-- editOptions -->");
1036
1037 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1038
1039 $wgOut->addHTML( "
1040 <div class='templatesUsed'>
1041 {$templates}
1042 </div>
1043 " );
1044
1045 if ( $wgUser->isLoggedIn() ) {
1046 /**
1047 * To make it harder for someone to slip a user a page
1048 * which submits an edit form to the wiki without their
1049 * knowledge, a random token is associated with the login
1050 * session. If it's not passed back with the submission,
1051 * we won't save the page, or render user JavaScript and
1052 * CSS previews.
1053 */
1054 $token = htmlspecialchars( $wgUser->editToken() );
1055 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1056 }
1057
1058
1059 if ( $this->isConflict ) {
1060 require_once( "DifferenceEngine.php" );
1061 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1062
1063 $de = new DifferenceEngine( $this->mTitle );
1064 $de->setText( $this->textbox2, $this->textbox1 );
1065 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1066
1067 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1068 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1069 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1070 }
1071 $wgOut->addHTML( "</form>\n" );
1072 if ( !$wgUser->getOption( 'previewontop' ) ) {
1073
1074 if ( $this->formtype == 'preview') {
1075 $this->showPreview();
1076 } else {
1077 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1078 }
1079
1080 if ( $this->formtype == 'diff') {
1081 $wgOut->addHTML( $this->getDiff() );
1082 }
1083
1084 }
1085
1086 wfProfileOut( $fname );
1087 }
1088
1089 /**
1090 * Append preview output to $wgOut.
1091 * Includes category rendering if this is a category page.
1092 * @access private
1093 */
1094 function showPreview() {
1095 global $wgOut;
1096 $wgOut->addHTML( '<div id="wikiPreview">' );
1097 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1098 $this->mArticle->openShowCategory();
1099 }
1100 $previewOutput = $this->getPreviewText();
1101 $wgOut->addHTML( $previewOutput );
1102 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1103 $this->mArticle->closeShowCategory();
1104 }
1105 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1106 $wgOut->addHTML( '</div>' );
1107 }
1108
1109 /**
1110 * Prepare a list of templates used by this page. Returns HTML.
1111 */
1112 function formatTemplates() {
1113 global $wgUser;
1114
1115 $fname = 'EditPage::formatTemplates';
1116 wfProfileIn( $fname );
1117
1118 $sk =& $wgUser->getSkin();
1119
1120 $outText = '';
1121 $templates = $this->mArticle->getUsedTemplates();
1122 if ( count( $templates ) > 0 ) {
1123 # Do a batch existence check
1124 $batch = new LinkBatch;
1125 foreach( $templates as $title ) {
1126 $batch->addObj( $title );
1127 }
1128 $batch->execute();
1129
1130 # Construct the HTML
1131 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1132 foreach ( $templates as $titleObj ) {
1133 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1134 }
1135 $outText .= '</ul>';
1136 }
1137 wfProfileOut( $fname );
1138 return $outText;
1139 }
1140
1141 /**
1142 * Live Preview lets us fetch rendered preview page content and
1143 * add it to the page without refreshing the whole page.
1144 * If not supported by the browser it will fall through to the normal form
1145 * submission method.
1146 *
1147 * This function outputs a script tag to support live preview, and
1148 * returns an onclick handler which should be added to the attributes
1149 * of the preview button
1150 */
1151 function doLivePreviewScript() {
1152 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1153 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1154 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1155 '"></script>' . "\n" );
1156 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1157 return "return !livePreview(" .
1158 "getElementById('wikiPreview')," .
1159 "editform.wpTextbox1.value," .
1160 '"' . $liveAction . '"' . ")";
1161 }
1162
1163 function getLastDelete() {
1164 $dbr =& wfGetDB( DB_SLAVE );
1165 $fname = 'EditPage::getLastDelete';
1166 $res = $dbr->select(
1167 array( 'logging', 'user' ),
1168 array( 'log_type',
1169 'log_action',
1170 'log_timestamp',
1171 'log_user',
1172 'log_namespace',
1173 'log_title',
1174 'log_comment',
1175 'log_params',
1176 'user_name', ),
1177 array( 'log_namespace' => $this->mTitle->getNamespace(),
1178 'log_title' => $this->mTitle->getDBkey(),
1179 'log_type' => 'delete',
1180 'log_action' => 'delete',
1181 'user_id=log_user' ),
1182 $fname,
1183 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1184
1185 if($dbr->numRows($res) == 1) {
1186 while ( $x = $dbr->fetchObject ( $res ) )
1187 $data = $x;
1188 $dbr->freeResult ( $res ) ;
1189 } else {
1190 $data = null;
1191 }
1192 return $data;
1193 }
1194
1195 /**
1196 * @todo document
1197 */
1198 function getPreviewText() {
1199 global $wgOut, $wgUser, $wgTitle, $wgParser;
1200
1201 $fname = 'EditPage::getPreviewText';
1202 wfProfileIn( $fname );
1203
1204 if ( $this->mTokenOk ) {
1205 $msg = 'previewnote';
1206 } else {
1207 $msg = 'session_fail_preview';
1208 }
1209 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1210 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1211 if ( $this->isConflict ) {
1212 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1213 }
1214
1215 $parserOptions = ParserOptions::newFromUser( $wgUser );
1216 $parserOptions->setEditSection( false );
1217
1218 # don't parse user css/js, show message about preview
1219 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1220
1221 if ( $this->isCssJsSubpage ) {
1222 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1223 $previewtext = wfMsg('usercsspreview');
1224 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1225 $previewtext = wfMsg('userjspreview');
1226 }
1227 $parserOptions->setTidy(true);
1228 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1229 $wgOut->addHTML( $parserOutput->mText );
1230 wfProfileOut( $fname );
1231 return $previewhead;
1232 } else {
1233 # if user want to see preview when he edit an article
1234 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1235 $this->textbox1 = $this->mArticle->getContent();
1236 }
1237
1238 $toparse = $this->textbox1;
1239
1240 # If we're adding a comment, we need to show the
1241 # summary as the headline
1242 if($this->section=="new" && $this->summary!="") {
1243 $toparse="== {$this->summary} ==\n\n".$toparse;
1244 }
1245
1246 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1247 $parserOptions->setTidy(true);
1248 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1249 $wgTitle, $parserOptions );
1250
1251 $previewHTML = $parserOutput->getText();
1252 $wgOut->addParserOutputNoText( $parserOutput );
1253
1254 wfProfileOut( $fname );
1255 return $previewhead . $previewHTML;
1256 }
1257 }
1258
1259 /**
1260 * @todo document
1261 */
1262 function blockedIPpage() {
1263 global $wgOut;
1264 $wgOut->blockedPage();
1265 }
1266
1267 /**
1268 * @todo document
1269 */
1270 function userNotLoggedInPage() {
1271 global $wgOut;
1272
1273 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1274 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1275 $wgOut->setArticleRelated( false );
1276
1277 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1278 $wgOut->returnToMain( false );
1279 }
1280
1281 /**
1282 * Creates a basic error page which informs the user that
1283 * they have to validate their email address before being
1284 * allowed to edit.
1285 */
1286 function userNotConfirmedPage() {
1287
1288 global $wgOut;
1289
1290 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1291 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1292 $wgOut->setArticleRelated( false );
1293 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1294 $wgOut->returnToMain( false );
1295 }
1296
1297 /**
1298 * @todo document
1299 */
1300 function spamPage ( $match = false )
1301 {
1302 global $wgOut;
1303 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1304 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1305 $wgOut->setArticleRelated( false );
1306
1307 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1308 if ( $match ) {
1309 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1310 }
1311 $wgOut->returnToMain( false );
1312 }
1313
1314 /**
1315 * @access private
1316 * @todo document
1317 */
1318 function mergeChangesInto( &$editText ){
1319 $fname = 'EditPage::mergeChangesInto';
1320 wfProfileIn( $fname );
1321
1322 $db =& wfGetDB( DB_MASTER );
1323
1324 // This is the revision the editor started from
1325 $baseRevision = Revision::loadFromTimestamp(
1326 $db, $this->mArticle->mTitle, $this->edittime );
1327 if( is_null( $baseRevision ) ) {
1328 wfProfileOut( $fname );
1329 return false;
1330 }
1331 $baseText = $baseRevision->getText();
1332
1333 // The current state, we want to merge updates into it
1334 $currentRevision = Revision::loadFromTitle(
1335 $db, $this->mArticle->mTitle );
1336 if( is_null( $currentRevision ) ) {
1337 wfProfileOut( $fname );
1338 return false;
1339 }
1340 $currentText = $currentRevision->getText();
1341
1342 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1343 $editText = $result;
1344 wfProfileOut( $fname );
1345 return true;
1346 } else {
1347 wfProfileOut( $fname );
1348 return false;
1349 }
1350 }
1351
1352 /**
1353 * Check if the browser is on a blacklist of user-agents known to
1354 * mangle UTF-8 data on form submission. Returns true if Unicode
1355 * should make it through, false if it's known to be a problem.
1356 * @return bool
1357 * @access private
1358 */
1359 function checkUnicodeCompliantBrowser() {
1360 global $wgBrowserBlackList;
1361 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1362 // No User-Agent header sent? Trust it by default...
1363 return true;
1364 }
1365 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1366 foreach ( $wgBrowserBlackList as $browser ) {
1367 if ( preg_match($browser, $currentbrowser) ) {
1368 return false;
1369 }
1370 }
1371 return true;
1372 }
1373
1374 /**
1375 * Format an anchor fragment as it would appear for a given section name
1376 * @param string $text
1377 * @return string
1378 * @access private
1379 */
1380 function sectionAnchor( $text ) {
1381 $headline = Sanitizer::decodeCharReferences( $text );
1382 # strip out HTML
1383 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1384 $headline = trim( $headline );
1385 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1386 $replacearray = array(
1387 '%3A' => ':',
1388 '%' => '.'
1389 );
1390 return str_replace(
1391 array_keys( $replacearray ),
1392 array_values( $replacearray ),
1393 $sectionanchor );
1394 }
1395
1396 /**
1397 * Shows a bulletin board style toolbar for common editing functions.
1398 * It can be disabled in the user preferences.
1399 * The necessary JavaScript code can be found in style/wikibits.js.
1400 */
1401 function getEditToolbar() {
1402 global $wgStylePath, $wgContLang, $wgJsMimeType;
1403
1404 /**
1405 * toolarray an array of arrays which each include the filename of
1406 * the button image (without path), the opening tag, the closing tag,
1407 * and optionally a sample text that is inserted between the two when no
1408 * selection is highlighted.
1409 * The tip text is shown when the user moves the mouse over the button.
1410 *
1411 * Already here are accesskeys (key), which are not used yet until someone
1412 * can figure out a way to make them work in IE. However, we should make
1413 * sure these keys are not defined on the edit page.
1414 */
1415 $toolarray=array(
1416 array( 'image'=>'button_bold.png',
1417 'open' => "\'\'\'",
1418 'close' => "\'\'\'",
1419 'sample'=> wfMsg('bold_sample'),
1420 'tip' => wfMsg('bold_tip'),
1421 'key' => 'B'
1422 ),
1423 array( 'image'=>'button_italic.png',
1424 'open' => "\'\'",
1425 'close' => "\'\'",
1426 'sample'=> wfMsg('italic_sample'),
1427 'tip' => wfMsg('italic_tip'),
1428 'key' => 'I'
1429 ),
1430 array( 'image'=>'button_link.png',
1431 'open' => '[[',
1432 'close' => ']]',
1433 'sample'=> wfMsg('link_sample'),
1434 'tip' => wfMsg('link_tip'),
1435 'key' => 'L'
1436 ),
1437 array( 'image'=>'button_extlink.png',
1438 'open' => '[',
1439 'close' => ']',
1440 'sample'=> wfMsg('extlink_sample'),
1441 'tip' => wfMsg('extlink_tip'),
1442 'key' => 'X'
1443 ),
1444 array( 'image'=>'button_headline.png',
1445 'open' => "\\n== ",
1446 'close' => " ==\\n",
1447 'sample'=> wfMsg('headline_sample'),
1448 'tip' => wfMsg('headline_tip'),
1449 'key' => 'H'
1450 ),
1451 array( 'image'=>'button_image.png',
1452 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1453 'close' => ']]',
1454 'sample'=> wfMsg('image_sample'),
1455 'tip' => wfMsg('image_tip'),
1456 'key' => 'D'
1457 ),
1458 array( 'image' =>'button_media.png',
1459 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1460 'close' => ']]',
1461 'sample'=> wfMsg('media_sample'),
1462 'tip' => wfMsg('media_tip'),
1463 'key' => 'M'
1464 ),
1465 array( 'image' =>'button_math.png',
1466 'open' => "\\<math\\>",
1467 'close' => "\\</math\\>",
1468 'sample'=> wfMsg('math_sample'),
1469 'tip' => wfMsg('math_tip'),
1470 'key' => 'C'
1471 ),
1472 array( 'image' =>'button_nowiki.png',
1473 'open' => "\\<nowiki\\>",
1474 'close' => "\\</nowiki\\>",
1475 'sample'=> wfMsg('nowiki_sample'),
1476 'tip' => wfMsg('nowiki_tip'),
1477 'key' => 'N'
1478 ),
1479 array( 'image' =>'button_sig.png',
1480 'open' => '--~~~~',
1481 'close' => '',
1482 'sample'=> '',
1483 'tip' => wfMsg('sig_tip'),
1484 'key' => 'Y'
1485 ),
1486 array( 'image' =>'button_hr.png',
1487 'open' => "\\n----\\n",
1488 'close' => '',
1489 'sample'=> '',
1490 'tip' => wfMsg('hr_tip'),
1491 'key' => 'R'
1492 )
1493 );
1494 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1495
1496 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1497 foreach($toolarray as $tool) {
1498
1499 $image=$wgStylePath.'/common/images/'.$tool['image'];
1500 $open=$tool['open'];
1501 $close=$tool['close'];
1502 $sample = wfEscapeJsString( $tool['sample'] );
1503
1504 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1505 // Older browsers show a "speedtip" type message only for ALT.
1506 // Ideally these should be different, realistically they
1507 // probably don't need to be.
1508 $tip = wfEscapeJsString( $tool['tip'] );
1509
1510 #$key = $tool["key"];
1511
1512 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1513 }
1514
1515 $toolbar.="document.writeln(\"</div>\");\n";
1516 $toolbar.="/*]]>*/\n</script>";
1517 return $toolbar;
1518 }
1519
1520 /**
1521 * Output preview text only. This can be sucked into the edit page
1522 * via JavaScript, and saves the server time rendering the skin as
1523 * well as theoretically being more robust on the client (doesn't
1524 * disturb the edit box's undo history, won't eat your text on
1525 * failure, etc).
1526 *
1527 * @todo This doesn't include category or interlanguage links.
1528 * Would need to enhance it a bit, maybe wrap them in XML
1529 * or something... that might also require more skin
1530 * initialization, so check whether that's a problem.
1531 */
1532 function livePreview() {
1533 global $wgOut;
1534 $wgOut->disable();
1535 header( 'Content-type: text/xml' );
1536 header( 'Cache-control: no-cache' );
1537 # FIXME
1538 echo $this->getPreviewText( );
1539 /* To not shake screen up and down between preview and live-preview */
1540 echo "<br style=\"clear:both;\" />\n";
1541 }
1542
1543
1544 /**
1545 * Get a diff between the current contents of the edit box and the
1546 * version of the page we're editing from.
1547 *
1548 * If this is a section edit, we'll replace the section as for final
1549 * save and then make a comparison.
1550 *
1551 * @return string HTML
1552 */
1553 function getDiff() {
1554 require_once( 'DifferenceEngine.php' );
1555 $oldtext = $this->mArticle->fetchContent();
1556 $newtext = $this->mArticle->replaceSection(
1557 $this->section, $this->textbox1, $this->summary, $this->edittime );
1558 $oldtitle = wfMsg( 'currentrev' );
1559 $newtitle = wfMsg( 'yourtext' );
1560 if ( $oldtext !== false || $newtext != '' ) {
1561 $de = new DifferenceEngine( $this->mTitle );
1562 $de->setText( $oldtext, $newtext );
1563 $difftext = $de->getDiff( $oldtitle, $newtitle );
1564 } else {
1565 $difftext = '';
1566 }
1567
1568 return '<div id="wikiDiff">' . $difftext . '</div>';
1569 }
1570
1571 /**
1572 * Filter an input field through a Unicode de-armoring process if it
1573 * came from an old browser with known broken Unicode editing issues.
1574 *
1575 * @param WebRequest $request
1576 * @param string $field
1577 * @return string
1578 * @access private
1579 */
1580 function safeUnicodeInput( $request, $field ) {
1581 $text = rtrim( $request->getText( $field ) );
1582 return $request->getBool( 'safemode' )
1583 ? $this->unmakesafe( $text )
1584 : $text;
1585 }
1586
1587 /**
1588 * Filter an output field through a Unicode armoring process if it is
1589 * going to an old browser with known broken Unicode editing issues.
1590 *
1591 * @param string $text
1592 * @return string
1593 * @access private
1594 */
1595 function safeUnicodeOutput( $text ) {
1596 global $wgContLang;
1597 $codedText = $wgContLang->recodeForEdit( $text );
1598 return $this->checkUnicodeCompliantBrowser()
1599 ? $codedText
1600 : $this->makesafe( $codedText );
1601 }
1602
1603 /**
1604 * A number of web browsers are known to corrupt non-ASCII characters
1605 * in a UTF-8 text editing environment. To protect against this,
1606 * detected browsers will be served an armored version of the text,
1607 * with non-ASCII chars converted to numeric HTML character references.
1608 *
1609 * Preexisting such character references will have a 0 added to them
1610 * to ensure that round-trips do not alter the original data.
1611 *
1612 * @param string $invalue
1613 * @return string
1614 * @access private
1615 */
1616 function makesafe( $invalue ) {
1617 // Armor existing references for reversability.
1618 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1619
1620 $bytesleft = 0;
1621 $result = "";
1622 $working = 0;
1623 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1624 $bytevalue = ord( $invalue{$i} );
1625 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1626 $result .= chr( $bytevalue );
1627 $bytesleft = 0;
1628 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1629 $working = $working << 6;
1630 $working += ($bytevalue & 0x3F);
1631 $bytesleft--;
1632 if( $bytesleft <= 0 ) {
1633 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1634 }
1635 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1636 $working = $bytevalue & 0x1F;
1637 $bytesleft = 1;
1638 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1639 $working = $bytevalue & 0x0F;
1640 $bytesleft = 2;
1641 } else { //1111 0xxx
1642 $working = $bytevalue & 0x07;
1643 $bytesleft = 3;
1644 }
1645 }
1646 return $result;
1647 }
1648
1649 /**
1650 * Reverse the previously applied transliteration of non-ASCII characters
1651 * back to UTF-8. Used to protect data from corruption by broken web browsers
1652 * as listed in $wgBrowserBlackList.
1653 *
1654 * @param string $invalue
1655 * @return string
1656 * @access private
1657 */
1658 function unmakesafe( $invalue ) {
1659 $result = "";
1660 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1661 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1662 $i += 3;
1663 $hexstring = "";
1664 do {
1665 $hexstring .= $invalue{$i};
1666 $i++;
1667 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1668
1669 // Do some sanity checks. These aren't needed for reversability,
1670 // but should help keep the breakage down if the editor
1671 // breaks one of the entities whilst editing.
1672 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1673 $codepoint = hexdec($hexstring);
1674 $result .= codepointToUtf8( $codepoint );
1675 } else {
1676 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1677 }
1678 } else {
1679 $result .= substr( $invalue, $i, 1 );
1680 }
1681 }
1682 // reverse the transform that we made for reversability reasons.
1683 return strtr( $result, array( "&#x0" => "&#x" ) );
1684 }
1685
1686 function noCreatePermission() {
1687 global $wgOut;
1688 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1689 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1690 }
1691
1692 }
1693
1694 ?>